//require formGetControlValue() function;

function ToolGUI (env, tools)
{
    this.Env = env;
    this.Tools = tools;
    this.tool_id = null;
    this.tool_form = null;
    this.submit_button = null;
    this.form = null;
    this.candidates_field = null;
    this.candidates = [];
    this.candidates_list = [];
    this.methods = {};

    /////////////////////////////////////////

    this.storeCandidates = function()
    {
        var candidates_field = this.form.elements[this.Env.candidates_control_name];
        if (candidates_field) {
            var candidates_ids = [];
            for (var i = 0; i < this.candidates.length; i++) {
                candidates_ids[candidates_ids.length] = this.candidates[i].id;
            }
            candidates_field.value = candidates_ids.join(',');
        }
    }

    this.isSelectedCandidates = function()
    {
        return this.candidates.length ? true : false;
    }

    this.presentCandidate = function(id)
    {
    	for (var i = 0; i < this.candidates.length; i++) {
    		if (this.candidates[i].id == id) {
    			return true;
    		}
    	}
    	return false;
    }

    this._addCandidate = function(obj)
    {
		this.onBeforeAddCandidate(obj);
		this.candidates[this.candidates.length] = obj;
        this.onAfterChangeCandidates();
    }

    this._delCandidate = function(id)
    {
    	for (var i = 0; i < this.candidates.length; i++) {
    		if (this.candidates[i].id == id) {
        		this.onBeforeDelCandidate(id);
    			this.candidates.splice(i, 1);
                this.onAfterChangeCandidates();
    			break;
    		}
    	}
    }

    this.onBeforeAddCandidate = function(obj)
    {
        var table = $('#' + this.Env.selected_candidates_table_id);
        var new_row_ref = null;
        if (table) {
            if (! this.candidates.length) {
                var old_table = table;
                table = $(this.drawSelectedCandidatesTable());
                $(old_table).replaceWith(table);
            }
            var tbody = $(table.find('tbody').get(0));
            if (tbody) {
                new_row_ref = $(this.drawSelectedCandidateRow(obj));
                tbody.append(new_row_ref);
                new_row_ref = new_row_ref.get(0);
            }
        }
        if (new_row_ref != null) {
            obj.row_ref = new_row_ref;
        }
    }

    this.onBeforeDelCandidate = function(id)
    {
        for (var i = 0; i < this.candidates.length; i++) {
            if (this.candidates[i].id == id) {
                if (this.candidates[i].row_ref) {
                    $(this.candidates[i].row_ref).remove();
                    this.candidates[i].row_ref = null;
                    this.candidates[i].control_ref.checked = false;
                }
            }
        }
        if (this.candidates.length <= 1) {
            var table = $('#' + this.Env.selected_candidates_table_id);
            $(table).replaceWith($(this.drawSelectedCandidatesEmpty()));
        }
    }

    this.onAfterChangeCandidates = function()
    {
        this.submitButtonSetStatus();
    }

    this.drawSelectedCandidatesEmpty = function()
    {
        var result = '';

        result += '<span id="' + this.Env.selected_candidates_table_id + '" class="additional_msg">' + this.Env.po.selected_candidate_absent + '</span>';

        return result ? $(result) : null;
    }

    this.drawSelectedCandidateRow = function(obj)
    {
        var result = '';

        result += '<tr>';
            result += '<td class="nw">';
            result +=     obj.surname_html;
            result += '</td>';
            result += '<td class="nw">';
            result +=     obj.name_html;
            result += '</td>';
            result += '<td class="nw">';
            result +=     obj.group_html;
            result += '</td>';
            result += '<td class="nw">';
            result +=     obj.test_name_html;
            result += '</td>';
            result += '<td class="nw">';
            result +=     obj.pass_date_html;
            result += '</td>';
            result += '<td class="nw actions">';
            result +=     '<table class="sys_clear" cellpadding="0">';
            result +=     '<tr class="sys_clear">';
            result +=     '<td class="sys_clear">';
            result +=         '<a href="#cancel" onclick="__ToolGUIEnv._delCandidate(' + obj.id + '); return false;" class="icon6 icon-link" title="' + this.Env.po.cancel + '"></a>';
            result +=     '</td>';
            result +=     '</tr>';
            result +=     '</table> ';
            result += '</td>';
        result += '</tr>';

        return result ? $(result) : null;
    }

    this.drawSelectedCandidatesEmptyTable = function()
    {
        var result = '';

        var headers = this.Env.selected_candidates_headers;

        result += '<table id="' + this.Env.selected_candidates_table_id + '" class="table" cellpadding="0">';
        result += '<thead>';
        result += '<tr>';
            result += '<th class="nw">';
            result +=     headers.surname;
            result += '</th>';
            result += '<th class="nw">';
            result +=     headers.name;
            result += '</th>';
            result += '<th class="nw">';
            result +=     headers.group;
            result += '</th>';
            result += '<th class="nw">';
            result +=     headers.test_name;
            result += '</th>';
            result += '<th class="nw">';
            result +=     headers.pass_date;
            result += '</th>';
            result += '<th class="nw actions">';
            result += '</th>';
        result += '</tr>';
        result += '</thead>';
        result += '<tbody>';

        result += '</tbody>';
        result += '</table>';

        return result ? $(result) : null;
    }

    this.drawSelectedCandidatesTable = function()
    {
        var table = this.drawSelectedCandidatesEmptyTable();
        if (table) {
            var tbody = $(table.find('tbody').get(0));
            if (tbody) {
                for (var i = 0; i < this.candidates.length; i++) {
                    var new_row_ref = $(this.drawSelectedCandidateRow(this.candidates[i]));
                    tbody.append(new_row_ref);
                    new_row_ref = new_row_ref.get(0);
                    this.candidates[i].row_ref = new_row_ref;
                }
            }
        }

        return table ? $(table) : null;
    }

    this.drawCandidates = function(url, data)
    {
        var table = this.getCandidates(url, data);
        if (table != null) {
            $('#' + this.Env.candidates_table_id).replaceWith(this.drawCandidatesTable(table));
            this.onNewCandidates();
        } else {
            $('#' + this.Env.candidates_table_id).replaceWith(this.drawCandidatesEmpty());
        }
    }

    this.drawCandidatesTable = function(table)
    {
        var result = '';

        result += '<tbody id="' + this.Env.candidates_table_id + '">';

        result += '<tr class="sys_clear">';
        result += '<td class="form-element-container sys_clear">';
        result += '<div class="form-element">';
        result += '<h5 class="no-margins no-color">';
        result += this.Env.selected_candidates_title;
        result += '</h5>';
        result += '</div>';
        result += '</td>';
        result += '</tr>';

        result += '<tr class="sys_clear">';
        result += '<td class="form-element-container sys_clear">';
        result += '<div class="form-element non-top-margin">';

        result += '<span id="' + this.Env.selected_candidates_table_id + '" class="additional_msg">' + this.Env.po.selected_candidate_absent + '</span>';

        result += '</div>';
        result += '</td>';
        result += '</tr>';

        result += '<tr class="sys_clear">';
        result += '<td class="form-element-container sys_clear">';
        result += '<div class="form-element">';
        result += '<h5 class="no-margins no-color">';
        result += this.Env.candidates_title;
        result += '</h5>';
        result += '</div>';
        result += '</td>';
        result += '</tr>';

        result += '<tr class="sys_clear">';
        result += '<td class="form-element-container sys_clear">';
        result += '<div class="form-element non-top-margin">';
        result += $(table).html();
        result += '</div>';
        result += '</td>';
        result += '</tr>';

        result += '</tbody>';

        result = result ? $(result) : null;
        if ((result != null) && (this.candidates.length)) {
            result.find('#' + this.Env.selected_candidates_table_id).replaceWith($(this.drawSelectedCandidatesTable()));
        }

        return result;
    }

    this.drawCandidatesEmpty = function()
    {
        var result = $(document.createElement('tbody'));

        result
            .attr('id', this.Env.candidates_table_id)
            .append(document.createElement('tr')).children()
                .attr('class', 'sys_clear')
                .append(document.createElement('td')).children()
                    .attr('class', 'form-element-container sys_clear')
                    .append(document.createElement('div')).children()
                        .attr('class', 'form-element')
        return result;
    }

    this.onCandidatesBrowise = function(url, control)
    {
        var control_name = null;
        var data = {};
            if (control) {
                if ((control.type != 'submit') || control.name.length) {
                    control_name = control.name;
                }
            }
            data = this.getCandidatesListFormValues(control_name);

        this.drawCandidates(url, data);
        return false;
    }

    this.getCandidatesListFormValues = function(control_name)
    {
        var hash = {};
        var elements = [];
        var tmp_elements = $('#' + this.Env.candidates_table_id).find('.filter_block_control');
        if (tmp_elements.length) {
            for (var i = 0; i < tmp_elements.length; i++) {
                elements[elements.length] = tmp_elements.get(i);
            }
        }
        for (var i = 0; i < elements.length; i++) {
            if (elements[i].name) {
                if ((elements[i].type != 'submit') || (elements[i].name == control_name)) {
                    var tmp_value = formValueOf(this.form, elements[i].name);
                    if (tmp_value !== null && tmp_value !== undefined) {
                        hash[elements[i].name] = tmp_value;
                    } else {
                        var tmp_value = elements[i].value;
                        if (tmp_value !== null && tmp_value !== undefined) {
                            hash[elements[i].name] = tmp_value;
                        }
                    }
                }
            }
        }

        return hash;
    }

    this.putCandidatesList = function(rows)
    {
        this.candidates_list = rows;
    }

    this.onNewCandidates = function()
    {
        var tmp_elements = $('#' + this.Env.candidates_table_id).find('.testings_for_select');
        var elements = [];
        if (tmp_elements.length) {
            for (var i = 0; i < tmp_elements.length; i++) {
                elements[elements.length] = tmp_elements.get(i);
            }
        }

        for (var i = 0; i < elements.length; i++) {
            var testing_id = 0;
            if (elements[i].id.indexOf('testing_id_') === 0) {
                testing_id = parseInt(elements[i].id.substr(('testing_id_').length));
            }
            var obj = this.getCandidateRefFromList(testing_id);
            if (obj != null) {
                var selected_candidate = this.getSelectedCandidateRef(obj.id);
                var checked = (selected_candidate != null) ? ' checked="1"' : '';
                var jquery_input = $('<input type="checkbox" value="' + testing_id + '" onclick="__ToolGUIEnv.onCandidateClick(' + obj.id + ');" ' + checked + ' />');
                $(elements[i]).replaceWith(jquery_input);
                obj.control_ref = jquery_input.get(0);
                if (selected_candidate != null) {
                    selected_candidate.control_ref = obj.control_ref;
                    obj = selected_candidate;
                }
            }
        }
    }

    this.getCandidateRefFromList = function(id)
    {
        for (var i = 0; i < this.candidates_list.length; i++) {
            if (this.candidates_list[i].id == id) {
                return this.candidates_list[i];
            }
        }

        return null;
    }

    this.getSelectedCandidateRef = function(id)
    {
        for (var i = 0; i < this.candidates.length; i++) {
            if (this.candidates[i].id == id) {
                return this.candidates[i];
            }
        }

        return null;
    }

    this.onCandidateClick = function(testing_id)
    {
        var obj = this.getCandidateRefFromList(testing_id);
        if (obj != null) {
            if (obj.control_ref.checked) {
                if (! this.presentCandidate(obj.id)) {
                    this._addCandidate(obj);
                }
            } else {
                if (this.presentCandidate(obj.id)) {
                    this._delCandidate(obj.id);
                }
            }
        }
    }

    this.getCandidates = function(url, data)
    {
        var result = null;
        if (! url) {
            url = this.Env.url_base + '/client/' + this.Env.client_id + '/test/' + this.tool_id + '/completed_testings_ajax';
        }

        data = data||{};

        if (this.tool_id != null) {

            var tmp_result = $.ajax({
            	async: false,
            	type: 'POST',
            	url: url,
            	data: data,
            	timeout: '3000' //ms
            });

            try {
                tmp_result = tmp_result.responseText;
            } catch (e) {}

        	if (tmp_result) {
                result = tmp_result;
        	}
        }

        return result;
    }

    /////////////////////////////////////////

    this.getCurrentId = function()
    {
        var value = formValueOf(this.tool_form, this.Env.select_tool_control_name);
        return typeof value == 'string' ? parseInt(value) : null;
    }

    this.isSelectedReport = function()
    {
        var value = formValueOf(this.form, this.Env.select_report_control_name);
        return typeof value == 'string';
    }

    this.isSelectedNorm = function()
    {
        var value = formValueOf(this.form, this.Env.select_norm_control_name);
        return typeof value == 'string';
    }

    this.attacheEvent = function()
    {
        var radios = this.tool_form.elements[this.Env.select_tool_control_name];
        if (radios.length == undefined) {
            radios = [radios];
        }
        for (var i = 0; i < radios.length; i++) {
            $(radios[i]).click(function() {
                __ToolGUIEnv.onClick();
            });
        }
    }

    this.onClick = function()
    {
        var current_id = this.getCurrentId();
        if (this.tool_id != current_id) {
            this.tool_id = current_id;
            this.onChange();
        }

        return true;
    }

    this.secondOnClick = function()
    {
        this.submitButtonSetStatus();
        return true;
    }

    this.submitButtonSetStatus = function()
    {
        this.submit_button.disabled = ! (
            this.isSelectedReport() &&
            this.isSelectedNorm()   &&
            this.isSelectedCandidates()
        );
        this.setConfirmString();
    }

    this.onChange = function()
    {
        this.onDraw();
    }

    this.getReports = function()
    {
        if (this.tool_id != null) {
            for (var i = 0; i < this.Tools.length; i++) {
                if (this.Tools[i].Test.id == this.tool_id) {
                    return this.Tools[i].Test.Reports;
                }
            }
        }

        return null;
    }

    this.getTool = function()
    {
        if (this.tool_id != null) {
            for (var i = 0; i < this.Tools.length; i++) {
                if (this.Tools[i].Test.id == this.tool_id) {
                    return this.Tools[i].Test;
                }
            }
        }

        return null;
    }

    this.getNorms = function()
    {
        if (this.tool_id != null) {
            for (var i = 0; i < this.Tools.length; i++) {
                if (this.Tools[i].Test.id == this.tool_id) {
                    return this.Tools[i].Test.Norms;
                }
            }
        }

        return null;
    }

    this.onDraw = function()
    {
        this.submit_button.disabled = true;
        this.drawCandidates();
        this.drawReports();
        this.drawNorms();
    }

    this.drawReports = function()
    {
        var rows = this.getReports();
        if (rows != null) {
            $('#reports_section').replaceWith($(this.drawReportsTable(rows)));
        } else {
            $('#reports_section').replaceWith($(this.drawReportsEmpty()));
        }
    }

    this.drawNorms = function()
    {
        var rows = this.getNorms();
        if (rows != null) {
            $('#norms_section').replaceWith($(this.drawNormsTable(rows)));
        } else {
            $('#norms_section').replaceWith($(this.drawNormsEmpty()));
        }
    }

    this.drawReportsEmpty = function()
    {
        var result = $(document.createElement('tbody'));

        result
            .attr('id', 'reports_section')
            .append(document.createElement('tr')).children()
                .attr('class', 'sys_clear')
                .append(document.createElement('td')).children()
                    .attr('class', 'form-element-container sys_clear')
                    .append(document.createElement('div')).children()
                        .attr('class', 'form-element')
        return result;
    }

    this.drawNormsEmpty = function()
    {
        var result = $(document.createElement('tbody'));

        result
            .attr('id', 'norms_section')
            .append(document.createElement('tr')).children()
                .attr('class', 'sys_clear')
                .append(document.createElement('td')).children()
                    .attr('class', 'form-element-container sys_clear')
                    .append(document.createElement('div')).children()
                        .attr('class', 'form-element')
        return result;
    }

    this.drawReportsTable = function(rows)
    {
        var fff = function(obj)
        {
            var result = $(document.createElement('tbody'));
            for (var i = 0; i < rows.length; i++) {
                var tr = $(document.createElement('tr'));
                var row = rows[i];
            	if (i % 2 != 0) {
            		tr.attr('class', 'altrow');
            	}
            	var input = $('<input type="radio" name="'+obj.Env.select_report_control_name+'" onclick="__ToolGUIEnv.secondOnClick();" value="'+row.id+'" />')
            	tr.append(document.createElement('td')).children()
            	       .attr('class', 'nw')
            	       .text(row.name)
            	   .after(document.createElement('td')).next()
            	       .attr('class', 'nw align-r')
            	       .html(row.html_price)
            	       //.text(row.price)
            	   .after(document.createElement('td')).next()
            	       .attr('class', 'nw')
            	   .append(input);

                result.append(tr);
            }

            return result;
        }

        var result = $(document.createElement('tbody'));

        result
            .attr('id', 'reports_section')
            .append(
                $(document.createElement('tr'))
                    .attr('class', 'sys_clear')
                    .append($(document.createElement('td'))
                        .attr('class', 'form-element-container sys_clear')
                        .append($(document.createElement('div'))
                            .attr('class', 'form-element')
                            .append($(document.createElement('h5'))
                                .attr('class', 'no-margins no-color')
                                .text(this.Env.reports_title)
                            )
                        )
                    )
            )
            .append(document.createElement('tr')).children().next()
                .attr('class', 'sys_clear')
                .append(document.createElement('td')).children()
                    .attr('class', 'form-element-container sys_clear')
                    .append(document.createElement('div')).children()
                        .attr('class', 'form-element non-top-margin')

                        .append(document.createElement('table')).children()
                            .attr('id', 'reports_table')
                            .attr('class', 'table')
                            .attr('cellpadding', '0')

                            .append(document.createElement('thead')).children()
                                .append(document.createElement('tr')).children()
                                    .append(document.createElement('th')).children()
                                        .attr('class', 'nw')
                                        .text(this.Env.reports_headers.name)
                                    .after(document.createElement('th')).next()
                                        .attr('class', 'nw')
                                        .text(this.Env.reports_headers.price)
                                    .after(document.createElement('th')).next()
                                        .attr('class', 'nw actions')
                                    .parent()
                            .parent()
                        .parent()
                            .append(fff(this));

        return result;
    }

    this.drawNormsTable = function(rows)
    {
        var fff = function(obj)
        {
            var result = $(document.createElement('tbody'));
            for (var i = 0; i < rows.length; i++) {
                var tr = $(document.createElement('tr'));
                var row = rows[i];
            	if (i % 2 != 0) {
            		tr.attr('class', 'altrow');
            	}
            	var input = $('<input type="radio" name="'+obj.Env.select_norm_control_name+'" onclick="__ToolGUIEnv.secondOnClick();" value="'+row.id+'" />')
            	tr.append(document.createElement('td')).children()
            	       .attr('class', 'nw')
            	       .text(row.name)
            	   .after(document.createElement('td')).next()
            	       .attr('class', 'nw')
            	   .append(input);

                result.append(tr);
            }

            return result;
        }

        var result = $(document.createElement('tbody'));

        result
            .attr('id', 'norms_section')
            .append(
                $(document.createElement('tr'))
                    .attr('class', 'sys_clear')
                    .append($(document.createElement('td'))
                        .attr('class', 'form-element-container sys_clear')
                        .append($(document.createElement('div'))
                            .attr('class', 'form-element')
                            .append($(document.createElement('h5'))
                                .attr('class', 'no-margins no-color')
                                .text(this.Env.norms_title)
                            )
                        )
                    )
            )
            .append(document.createElement('tr')).children().next()
                .attr('class', 'sys_clear')
                .append(document.createElement('td')).children()
                    .attr('class', 'form-element-container sys_clear')
                    .append(document.createElement('div')).children()
                        .attr('class', 'form-element non-top-margin')

                        .append(document.createElement('table')).children()
                            .attr('id', 'norms_table')
                            .attr('class', 'table')
                            .attr('cellpadding', '0')

                            .append(document.createElement('thead')).children()
                                .append(document.createElement('tr')).children()
                                    .append(document.createElement('th')).children()
                                        .attr('class', 'nw')
                                        .text(this.Env.norms_headers.name)
                                    .after(document.createElement('th')).next()
                                        .attr('class', 'nw actions')
                                    .parent()
                            .parent()
                        .parent()
                            .append(fff(this));

        return result;
    }

    this.getReport = function()
    {
        var selected_id = formValueOf(this.form, this.Env.select_report_control_name);
        typeof selected_id == 'string' ? parseInt(selected_id) : null;

        if (! selected_id) {
            return null;
        }

        var rows = this.getReports();
        if (rows != null) {
            for (var i = 0; i < rows.length; i++) {
                var row = rows[i];
                if (row.id == selected_id) {
                    return row;
                }
            }
        } else {
            return null;
        }
    }

    this.setConfirmString = function()
    {
        var report = this.getReport();
        if (! report) {
            return;
        }
        var num_candidates = this.candidates.length;
        var num_candidates_txt = num_candidates + ' ' + this.Env.po['candidate_plurar_' + plurar_mode_ru(num_candidates)];

        var total_sum = Number(report.add_price) * num_candidates + Number(report.price);

        var total_sum_txt = format_decimal(parse_decimal_str(total_sum));

        var confirm_msg = (

            this.Env.po.confirm_begin +

                report.txt_price +

            this.Env.po.confirm_middle_1 +

                report.add_price +

            this.Env.po.confirm_middle_2 +

                num_candidates_txt +

            this.Env.po.confirm_middle_3 +

                total_sum_txt + ' ' + this.Env.po.currencyTXT +

            this.Env.po.confirm_end

        );

        $(this.submit_button).unbind("click");
        $(this.submit_button).bind("click", function(){if (!confirm(confirm_msg)) return false; __ToolGUIEnv.onSubmit();});
    }

    this.init = function()
    {
        this.tool_form      = $('#' + this.Env.tool_form_id).get(0);
        this.form           = this.tool_form;
        this.submit_button  = $('#' + this.Env.submit_button_id).get(0);

        this.attacheEvent();
        this.onDraw();
    }

    this.onSubmit = function()
    {
        this.storeCandidates();
    }

    this.init();
}

var __ToolGUIEnv;